package cn.kai.basic.util;

import org.junit.Test;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;

/**
 * @Author Kai
 * @Date 2022/6/14 10:37
 * @PackageName:cn.kai.basic.util
 * @ClassName: MyMailUtil
 * @Description: 邮件发送工具类
 * @Version 1.0
 */
public class MyMailUtil {


    public static void simpleMail(JavaMailSender javaMailSender,String sendMail,String subject,String contentText,String acceptMail){
//        JavaMailSender javaMailSender = (JavaMailSender)ApplicationContextUtils.getBean("JavaMailSender");

        SimpleMailMessage mailMessage = new SimpleMailMessage();
        //设置发送人
        mailMessage.setFrom(sendMail);
        //邮件主题
        mailMessage.setSubject(subject);
        //邮件内容
        mailMessage.setText(contentText);
        //收件人
        mailMessage.setTo(acceptMail);

        javaMailSender.send(mailMessage);
    }


    public static void complexMail(JavaMailSender javaMailSender,String sendMail,String subject,String contentText,Boolean htmlBoolean,String fileName,File file,String acceptMail) throws Exception {
        //创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //发送复杂邮件的工具类
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
        helper.setFrom(sendMail);
        helper.setSubject(subject);
        //第二个参数 true 代表是否是一个html内容
        helper.setText(contentText,htmlBoolean);
        //添加附件
        if (file != null){
            helper.addAttachment(fileName,file);
        }
        //收件人
        helper.setTo(acceptMail);
        //发送邮件
        javaMailSender.send(mimeMessage);
    }
}
